#include <iostream>
#include <fstream>

#include "contacts.pb.h"
//unknown_field还包含在google::protobuf命名空间中
#include "google/protobuf/unknown_field_set.h"

using namespace google::protobuf;

#define CONTACTS_FILE "../contacts.bin"

void printfContact(const contacts2::Contacts &contact)
{
    for(int i = 0; i < contact.peoples_size(); ++i)
    {
        std::cout << "----------联系人" << i + 1 << "----------" << std::endl;
        contacts2::PeopleInfo people = contact.peoples(i);
        std::cout << "姓名: " << people.name() << std::endl;
        std::cout << "年龄: " << people.age() << std::endl;
        //电话
        for(int j = 0; j < people.phone_size(); ++j)
        {
            const contacts2::PeopleInfo_Phone &phone = people.phone(j);
            std::cout << j + 1 << "电话: " << phone.phone()
                      << "  (" << phone.PhoneType_Name(phone.type()) << ")" << std::endl;
        }

        //未知字段
        const Reflection *reflection = people.GetReflection();
        const UnknownFieldSet &set = reflection->GetUnknownFields(people);
        for(int i = 0; i < set.field_count(); ++i)
        {
            const UnknownField field = set.field(i);
            std::cout << "未知字段" << i + 1 << ": 编号" << field.number()
                      << " 类型: " << field.type() << std::endl;
            std::cout << "值: ";
            switch (field.type())
            {
            case UnknownField::Type::TYPE_VARINT :
                std::cout << field.varint() << std::endl;
                break;
            case UnknownField::Type::TYPE_LENGTH_DELIMITED :
                std::cout << field.length_delimited() << std::endl;
                break;
            default:
                break;
            }
        }
    }
}

int main()
{
    //读取通讯录文件，并反序列化
    contacts2::Contacts contact;
    std::ifstream input(CONTACTS_FILE, std::ios::in | std::ios::binary);
    if(!contact.ParseFromIstream(&input))
    {
        std::cerr << "反序列化通讯录文件失败" << std::endl;
        input.close();
        return -1;
    }
    //打印联系人信息
    printfContact(contact);
}